package link.chengguo.orangemall.common.aop;

/**
 * @Author: 钟业海
 * @Date: 2020/8/18 19:01
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import link.chengguo.orangemall.api.ApiResult;
import link.chengguo.orangemall.common.bean.LocalUser;
import link.chengguo.orangemall.modules.domain.OrangeStoreProductBrowse;
import link.chengguo.orangemall.modules.product.vo.ProductVo;
import link.chengguo.orangemall.modules.service.OrangeStoreProductBrowseService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 浏览记录aop
 * @author chengguo
 * @since 2020-06-02
 */
@Aspect
@Component
@Slf4j
public class ProductBrowseAspect {

    @Autowired
    OrangeStoreProductBrowseService browseService;

    @AfterReturning(value = "execution(* link.chengguo.orangemall.modules.product.rest.StoreProductController.detail(..))",returning = "keys")
    public void around(JoinPoint jp,Object keys){
        try{
            if(keys instanceof ApiResult){
                ProductVo productVo = ((ApiResult<ProductVo>) keys).getData();
                if(productVo != null){
                    Long pid = productVo.getStoreInfo().getId();
                    Long uid = LocalUser.getUser().getUid();
                    OrangeStoreProductBrowse browse = browseService.getOne(new QueryWrapper<OrangeStoreProductBrowse>().eq("uid",uid).eq("product_id",pid));
                    if(browse != null){
                        browse.setCount(browse.getCount()+1);
                        browseService.updateById(browse);
                    }else{
                        browse = new OrangeStoreProductBrowse();
                        browse.setUid(uid);
                        browse.setProductId(pid);
                        browse.setCount(1L);
                        browseService.save(browse);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
